/** @format */

import { computed, onMounted, ref } from 'vue'

import { CACHE_KEY } from '../contants/configCont'
import { UserService } from '../services/userService'
import { getCurrentPage } from '../utils/commonUtils'
import { useCache } from './useCache'

const userService = new UserService()
const cache = useCache<any[]>(CACHE_KEY.userInfo, -1)
const userInfo = ref<any>(cache.getItem() || {})
const userContent = computed(() => {
  return userInfo.value.content || {}
})
const repositories = computed(() => {
  return (
    userContent.value?.repositories || [
      // 默认为空时的数据
      { owner: 'tunie', repo: 'nestjs-starter', name: 'nestjs-starter' },
    ]
  )
})
// 用户配置
const userConf = computed(() => {
  return userContent.value?.config || {}
})

const imgs = computed(() => {
  return userContent.value?.imgs || []
})

let hasLoad = false
const getUserInfo = async () => {
  if (hasLoad) return
  hasLoad = true
  const res = await userService.getUser()
  userInfo.value = res
  cache.setItem(res)
}

const isAdmin = computed(() => {
  return userInfo.value.opendId === 'o80_15UYDsNo4QpqZfsKEQB8_Opo'
})

const isCustomHome = computed(() => {
  const currentPath = getCurrentPage()
  const conf = userConf.value
  // 响应处理
  if (!conf?.homePath) {
    return currentPath === '/pages/index/index'
  }

  const r1 = decodeURIComponent(decodeURIComponent(currentPath))
  const r2 = decodeURIComponent(decodeURIComponent(conf.homePath))
  const result = r1 === r2
  return result
})

const updateUserInfo = async (data) => {
  const currentUserInfo = { ...userInfo.value }
  currentUserInfo.content = {
    ...currentUserInfo.content,
    ...data,
  }

  const updateRes = await userService.updateUser(currentUserInfo)
  const { sha } = updateRes.data?.content || {}
  currentUserInfo.sha = sha

  userInfo.value = currentUserInfo

  // 更新缓存
  cache.setItem(userInfo.value)
}

const isSameRepo = (item1, item2) => {
  return item1.owner === item2.owner && item1.repo === item2.repo
}

const resHasCheck = (owner, repo) => {
  return repositories.value.some((r) => isSameRepo(r, { owner, repo }))
}

const addRes = async ({ owner, repo, name, toast, desc }) => {
  if (resHasCheck(owner, repo)) {
    toast?.show('已存在，无须操作')
    return
  }

  updateUserInfo({
    repositories: [
      ...repositories.value,
      { owner, repo, name: name || repo, desc },
    ],
  })

  toast?.show('操作成功')
}

const updateUserConf = async (data) => {
  await updateUserInfo({
    config: {
      ...userConf.value,
      ...data,
    },
  })
}

const imgHasCheck = (url) => {
  return imgs.value.some((img) => img.url === url)
}

const addImg = async (img) => {
  if (imgHasCheck(img.url)) {
    return
  }
  updateUserInfo({
    imgs: [...imgs.value, img],
  })
}

export function useUserService() {
  // 从缓存加载知库列表

  onMounted(() => {
    // 取得用户数据
    getUserInfo()
  })

  return {
    isAdmin,
    isCustomHome,
    userInfo,
    repositories,
    userConf,
    resHasCheck,
    getUserInfo,
    updateUserInfo,
    addRes,
    updateUserConf,
    addImg,
  }
}
